/*
 * @Description: EXCEL表创建面板
 * @Author: Rfan
 * @Date: 2022-05-06 12:05:58
 * @LastEditTime: 2022-08-09 19:43:23
 */

import { useEffect, useState } from 'react';
import { Button, Divider, Form, Input, Select, Space, Table, Tabs, Typography } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { v4 as uuidv4 } from 'uuid';
import { delItemById, editItemById } from '@/utils/list';
import { indexToTitle, jsonClone } from '@/utils';
import { useBatchManageContext } from '../../../../contexts/BatchManageContext';
import { addExcelTemplate, editExcelTemplate } from '@/api/accession';
import { IMetadata } from '@/interfaces/metadata';
import { ILevel } from '@/interfaces/archiveType';

const { TabPane } = Tabs;
const { Column } = Table;
const { Option } = Select;

class ExcelItem {
  key: string;

  column: string = '';

  fieldName: string = null;

  fieldOperator: string = '';

  title: string = null;

  titleOperator: string = '';

  constructor(idx: number) {
    this.key = uuidv4();
  }
}

const ExcelPane = (props: any) => {
  const { levelList, levelMetadata, form, tplData, setIndexTab, updateTemplate } = props;
  const { activeBatch } = useBatchManageContext();

  // 当前选中的tab
  const [currentTab, setCurrentTab] = useState<string>('');
  // excel表头下拉框相关
  const [items, setItems] = useState([]);
  // 表格内容
  const [initTable, setInitTable] = useState([]);
  // 新增的表头字段
  const [name, setName] = useState('');
  // excel列与元数据字段关系
  const [colRelation, setColRelation] = useState<any[]>([]);

  useEffect(() => {
    if (tplData?.id) {
      tplData.levelList.forEach((level: any) => {
        // levelList 增加key
        level.relationList.forEach((item: any) => {
          item = {
            ...item,
            key: item.column + item.title
          };
        });
      });
      const levelList = tplData.levelList.map((level: any) => {
        return level.relationList.forEach((item: any) => {
          return {
            ...item,
            key: item.column + item.title
          };
        });
      });
      console.log('excel data', levelList);

      form.setFieldsValue(tplData);
      setColRelation(tplData.levelList);
    } else {
      form.setFieldsValue({
        tplName: '',
        archiveTypeId: activeBatch.archiveTypeId
      });
    }
  }, [tplData]);

  useEffect(() => {
    if (levelList?.length > 0) {
      const highestLevel = levelList.find((level: ILevel) => level.levelNum === 1);
      setCurrentTab(`${highestLevel?.level}`);
    }
  }, [levelList]);

  useEffect(() => {
    if (currentTab && JSON.stringify(levelMetadata) !== '{}') {
      setItems(levelMetadata[currentTab] || []);
      // TODO: 后期重新整理数据
      const currentData = colRelation.find((item: any) => item.level === parseInt(currentTab, 10));
      setInitTable(
        currentData?.relationList.map((_item: any) => ({
          ..._item,
          key: _item.column + _item.title
        })) || []
      );
    }
  }, [currentTab, levelMetadata]);

  /**
   * @description: tab切换
   * @param {string} key 选中的tab的key
   */
  const tabsChange = (key: string) => {
    saveTableForm();
    setCurrentTab(key);
  };

  /**
   * @description: 保存excel与元数据映射关系
   */
  const saveTableForm = () => {
    setColRelation((state: any) => {
      const newState = jsonClone(state);
      console.log({ newState });
      if (newState.length > 0) {
        let flag = false;
        newState.forEach((item: any) => {
          if (item.level === parseInt(currentTab, 10)) {
            item.relationList = initTable;
            flag = true;
          }
        });
        if (!flag) {
          newState.push({
            level: parseInt(currentTab, 10),
            relationList: initTable
          });
        }
      } else {
        newState.push({
          level: parseInt(currentTab, 10),
          relationList: initTable
        });
      }
      return newState;
    });
    updateTemplate((state: any) => ({
      ...state,
      levelList: colRelation
    }));
  };

  /**
   * @description: 添加选项输入框变化事件
   * @param {any} evt 输入事件
   */
  const onNameChange = (evt: any) => {
    setName(evt.target.value);
  };

  /**
   * @description: 新增一个选项
   * @param {any} evt 按钮点击事件
   */
  const addItem = (evt: any) => {
    evt.preventDefault();
    if (name) {
      setItems([...items, { field_desc: name }]);
      setName('');
    }
  };

  /**
   * @description: 保存单元格操作选择的内容
   * @param {any} row
   */
  const handleSave = (row: any) => {
    const newData = [...initTable];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    setInitTable(newData);
  };

  /**
   * @description: 清空数据
   * @param {string} key 条目key，用于定位数据
   * @param {any} record 原始条目数据
   */
  const clearItem = (key: string, record: any) => {
    const initData: any = {
      fieldName: null,
      fieldOperator: '',
      title: null,
      titleOperator: ''
    };
    setInitTable(editItemById(key, { ...record, ...initData }, initTable, 'key'));
  };

  /**
   * @description: 清空全部数据
   */
  const clearAll = () => {
    const initData: any = {
      fieldName: null,
      fieldOperator: '',
      title: null,
      titleOperator: ''
    };
    setInitTable((state) => state.map((item) => ({ ...item, ...initData })));
  };

  const deleteItem = (key: string) => {
    setInitTable(delItemById(key, initTable, 'key'));
  };

  const getFTypeByFName = (level: number, name: string) =>
    levelMetadata[level].find((item: IMetadata) => item.field_name === name)?.field_type;

  const onFinish = (values: any) => {
    console.log('finish form', values, colRelation);
    saveTableForm();
    if (!values.archiveTypeId) {
      values.archiveTypeId = activeBatch.archiveTypeId;
    }
    const levelList = colRelation.map((item: any): any => {
      return {
        ...item,
        relationList: item.relationList.map((col: any, idx: number): any => {
          return {
            column: `${indexToTitle(idx + 1)}1`,
            fieldName: col.fieldName,
            fieldOperator: col.fieldOperator,
            fieldType: getFTypeByFName(item.level, col.fieldName),
            sortNo: idx + 1,
            title: col.title,
            titleOperator: col.titleOperator
          };
        })
      };
    });
    const params = { ...tplData, ...values, tplType: 0 };
    params.levelList = levelList;
    if (!tplData?.id) {
      addExcelTemplate(params).then((res) => {
        updateTemplate(res.data);
        setIndexTab((state: string) => `${parseInt(state, 10) + 1}`);
      });
    } else {
      editExcelTemplate(params).then((res) => {
        setIndexTab((state: string) => `${parseInt(state, 10) + 1}`);
      });
    }
  };

  const operations = (
    <Space>
      <Button
        onClick={() => {
          setInitTable((state) => [...state, new ExcelItem(state.length)]);
        }}
      >
        增加表头
      </Button>
      <Button
        onClick={() => {
          clearAll();
        }}
      >
        清空
      </Button>
    </Space>
  );

  return (
    <>
      <Form form={form} onFinish={onFinish}>
        <Form.Item name="tplName" label="模板名称" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name="archiveTypeId" label="选择档案库">
          <Select disabled style={{ width: '100%' }}>
            <Option value={activeBatch?.archiveType?.id}>{activeBatch?.archiveType?.atName}</Option>
          </Select>
        </Form.Item>
      </Form>
      <Tabs activeKey={currentTab} tabBarExtraContent={operations} onChange={tabsChange}>
        {levelList.map((level: ILevel) => (
          <TabPane tab={level.levelName} key={level.level}>
            <Table dataSource={initTable} size="small" pagination={false} bordered>
              <Column
                title="EXCEL列"
                key="excelCol"
                align="center"
                render={(_val, _record, idx) => `${indexToTitle(idx + 1)}1`}
              />
              <Column
                title="表头字段"
                dataIndex="title"
                key="title"
                align="center"
                render={(val, record: ILevel) => (
                  <Select
                    value={val}
                    style={{ width: 200 }}
                    placeholder="请选择字段"
                    size="small"
                    dropdownRender={(menu) => (
                      <>
                        <Space align="center" style={{ padding: '0 8px 4px' }}>
                          <Input placeholder="选择字段" value={name} onChange={onNameChange} />
                          <Typography.Link
                            onClick={(evt) => {
                              addItem(evt);
                            }}
                            style={{ whiteSpace: 'nowrap' }}
                          >
                            <PlusOutlined /> 增加
                          </Typography.Link>
                        </Space>
                        <Divider style={{ margin: '8px 0' }} />
                        {menu}
                      </>
                    )}
                    onChange={(value) => {
                      handleSave({ ...record, title: value });
                    }}
                  >
                    {items.map((item: any) => (
                      <Option key={item.field_name} value={item.field_desc}>
                        {item.field_desc}
                      </Option>
                    ))}
                  </Select>
                )}
              />
              <Column
                title="对应库内字段"
                dataIndex="fieldName"
                key="fieldName"
                align="center"
                render={(val, record: any) => (
                  <Select
                    value={val}
                    style={{ width: 140 }}
                    size="small"
                    placeholder="请选择字段"
                    onChange={(value) => {
                      handleSave({ ...record, fieldName: value });
                    }}
                  >
                    {levelMetadata[level.level] &&
                      levelMetadata[level.level].map((item: IMetadata) => (
                        <Option key={item.field_name} value={item.field_name}>
                          {item.field_desc}
                        </Option>
                      ))}
                  </Select>
                )}
              />
              <Column
                title="操作"
                dataIndex="action"
                key="action"
                align="center"
                render={(_val, record: any) => (
                  <Space size="small">
                    <Button
                      type="link"
                      size="small"
                      onClick={() => {
                        clearItem(record.key, record);
                      }}
                    >
                      清空
                    </Button>
                    <Button
                      type="link"
                      size="small"
                      danger
                      onClick={() => {
                        deleteItem(record.key);
                      }}
                    >
                      删除
                    </Button>
                  </Space>
                )}
              />
            </Table>
          </TabPane>
        ))}
      </Tabs>
    </>
  );
};

export default ExcelPane;
